from sqlalchemy import create_engine, Column, Integer, String, Text, DateTime, Float, Boolean, JSON
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.sql import func
from app.core.config import config

Base = declarative_base()

class UserProfile(Base):
    """用户画像表"""
    __tablename__ = "user_profiles"
    
    user_id = Column(String(50), primary_key=True)
    username = Column(String(100))
    preferred_models = Column(JSON, default=list)  # 偏好模型列表
    usage_stats = Column(JSON, default=dict)      # 使用统计
    created_at = Column(DateTime, default=func.now())
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now())

class InteractionRecord(Base):
    """交互记录表"""
    __tablename__ = "interaction_records"
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    user_id = Column(String(50), index=True)
    session_id = Column(String(100), index=True)
    user_input = Column(Text)
    model_used = Column(String(100))
    model_response = Column(Text)
    intent_type = Column(String(50))              # 意图类型
    processing_time = Column(Float)               # 处理时间
    user_feedback = Column(Integer)               # 用户反馈：1赞，-1踩，0无
    created_at = Column(DateTime, default=func.now())

class ModelUsageStats(Base):
    """模型使用统计表"""
    __tablename__ = "model_usage_stats"
    
    model_name = Column(String(100), primary_key=True)
    total_requests = Column(Integer, default=0)
    avg_processing_time = Column(Float, default=0.0)
    success_rate = Column(Float, default=1.0)
    user_rating_avg = Column(Float, default=0.0)
    last_used = Column(DateTime, default=func.now())

class TrainingData(Base):
    """训练数据表"""
    __tablename__ = "training_data"
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    source_record_id = Column(Integer)            # 原始记录ID
    model_name = Column(String(100))
    input_text = Column(Text)
    output_text = Column(Text)
    quality_score = Column(Float)                 # 数据质量评分
    selected_for_training = Column(Boolean, default=False)
    exported = Column(Boolean, default=False)
    created_at = Column(DateTime, default=func.now())

# 数据库引擎
engine = create_engine(
    config.get('DATABASE_URL'),
    echo=config.get_bool('DATABASE_ECHO')
)